<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert
        title="消息提示的文案"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 步骤条区域 -->
      <el-steps :active="activeIndex - 0" align-center finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="属性属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 左边的tabs标签页 -->
      <el-form
        :model="addGoodsForm"
        :rules="addGoodsFormRules"
        ref="addGoodsFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          v-model="activeIndex"
          tab-position="left"
          :before-leave="beforeTabLeave"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <!-- 基本信息表单 -->
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addGoodsForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addGoodsForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addGoodsForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader
                v-model="addGoodsForm.goods_cat"
                :options="cateList"
                :props="selectedProps"
                @change="cateChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 动态商品属性信息 复选框组 -->
            <!-- v-for="(item, i) in manyParamsData"  -- tag 使用的-->
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyParamsData"
              :key="item.attr_id"
            >
              <!-- 以 tag 的方式展示商品属性的详情 -->
              <!-- <el-tag
                v-for="(bag, ii) in item.attr_vals"
                :key="ii"
                closable
                @close="deleteAttrVal(i, ii)"
              >
                {{ bag }}
              </el-tag> -->

              <!-- 以 checkbox 多选框的方式展示商品属性的详情 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :v-model="true"
                  :label="bag"
                  v-for="(bag, ii) in item.attr_vals"
                  :key="ii"
                  border
                  @change="nowAttrVals"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <!-- 静态商品信息表单 -->
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyParamsData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 上传图片 -->
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="addGoodsForm.goods_introduce"></quill-editor>
            <!-- 添加商品的按钮 -->
            <el-button type="primary" class="btnAdd" @click="add"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 预览图片对话框 -->
    <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
      <img :src="PreviewPath" alt="" class="previewImg" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  name: 'Add',
  data() {
    return {
      // 当前步骤条的活动位置
      activeIndex: '0',
      // 添加商品的表单数据
      addGoodsForm: {
        goods_name: '',
        goods_price: '',
        goods_weight: '',
        goods_number: '',
        // 选中的父级分类的 id 数组
        goods_cat: '',
        pics: [],
        goods_introduce: '',
        attrs: [],
      },
      // 添加商品的表单数据校验规则
      addGoodsFormRules: {
        goods_name: [
          {
            required: true,
            message: '请输入商品名称',
            trigger: 'blur',
          },
        ],
        goods_price: [
          {
            required: true,
            message: '请输入商品价格',
            trigger: 'blur',
          },
        ],
        goods_weight: [
          {
            required: true,
            message: '请输入商品重量',
            trigger: 'blur',
          },
        ],
        goods_number: [
          {
            required: true,
            message: '请输入商品数量',
            trigger: 'blur',
          },
        ],
        goods_cat: [
          {
            required: true,
            message: '请输入商品分类',
            trigger: 'blur',
          },
        ],
      },
      // 所有的商品数据列表
      cateList: [],
      // 多级选择器的配置对象
      selectedProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      // 现在多级选择器选中的动态面板的属性信息
      manyParamsData: [],
      // 现在多级选择器选中的静态面板的属性信息
      onlyParamsData: [],
      // 定义一个标签页
      newActiveName: '',
      // 图片上传组件的headers请求头对象
      headerObj: {
        Authorization: window.sessionStorage.getItem('token'),
      },
      // 隐藏图片预览对话框
      previewVisible: false,
      // 定义预览图片路径
      PreviewPath: '',
    }
  },
  created() {
    this.getCateList()
  },
  mounted() {
    this.$bus.$on('SaveList', this.add())
  },
  methods: {
    // 获取所有的商品信息事件
    async getCateList() {
      const { data: res } = await this.$http.get('categories')

      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }

      this.cateList = res.data
    },
    // 监听改变多级选择器数据事件
    cateChange() {
      //   console.log(this.addGoodsForm.goods_cat)
      if (this.addGoodsForm.goods_cat.length < 2) {
        this.addGoodsForm.goods_cat = []
      }
    },
    // 切换 tabs 的阻止条件事件
    beforeTabLeave(activeName, oldActiveName) {
      //   console.log(activeName, oldActiveName)
      if (oldActiveName === '0' && this.addGoodsForm.goods_cat.length < 2) {
        this.$message.error('请先选择商品分类')
        return false
      }
    },
    // 获取多级选择器选中的数据的信息事件
    async tabClick() {
      // 定义当前选中的标签页
      if (this.activeIndex === '1') {
        this.newActiveName = 'many'
        this.getNewSelectedData()
      } else if (this.activeIndex === '2') {
        this.newActiveName = 'only'
        this.getNewSelectedData()
      }
    },
    // 获取现在的级联选择器选中的商品数据详情
    async getNewSelectedData() {
      // 获取此时级联选择器选中的商品 id
      if (this.addGoodsForm.goods_cat.length >= 2) {
        this.cateId =
          this.addGoodsForm.goods_cat[this.addGoodsForm.goods_cat.length - 1]
        // console.log(this.cateId)
      }
      // 获取商品属性的详情
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.newActiveName },
        }
      )

      // console.log(res)

      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }

      // 遍历数组，得到字符串数组
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals
          ? item.attr_vals.replace(/[ ]/g, ',').split(',')
          : []
      })

      // console.log(res.data)

      // 以不同的标签页获取不同的商品属性详情
      if (this.newActiveName === 'many') {
        this.manyParamsData = res.data
      }
      if (this.newActiveName === 'only') {
        this.onlyParamsData = res.data
        // console.log(this.onlyParamsData)
      }
    },
    // 关闭单个属性商品信息(以 tag 的方式展示商品属性的详情)
    // #region
    /* async deleteAttrVal(i, ii) {
      // console.log(i, ii)
      // console.log(this.manyParamsData[i].attr_vals[ii])

      this.manyParamsData[i].attr_vals.splice(ii, 1)

      // console.log(this.manyParamsData)

      // 将修改的参数保存到服务器上
      if (this.manyParamsData) {
        const { data: res } = await this.$http.put(
          `categories/${this.manyParamsData[i].cat_id}/attributes/${this.manyParamsData[i].attr_id}`,
          {
            attr_name: this.manyParamsData[i].attr_name,
            attr_sel: this.manyParamsData[i].attr_sel,
            attr_vals: this.manyParamsData[i].attr_vals.join(' '),
          }
        )

        // console.log(res)

        if (res.meta.status !== 200) {
          return this.$message.error('删除参数项失败！')
        }
      }
    }, */
    //#endregion
    nowAttrVals(newValue) {
      // console.log(newValue)
    },
    // 监听图片上传成功事件
    async handleSuccess(response) {
      // console.log(response)
      // console.log(response.data.tmp_path)
      // console.log(this.addGoodsForm.pics)

      const picInfo = { pic: response.data.tmp_path }
      this.addGoodsForm.pics.push(picInfo)

      console.log(this.addGoodsForm)
    },
    // 上传图片预览事件
    handlePreview(file) {
      console.log(file, file.url)
      this.PreviewPath = file.url

      // 显示图片预览对话框
      this.previewVisible = true
    },
    // 移除上传的图片事件
    handleRemove(file) {
      // console.log(file)

      const picPath = file.response.data.tmp_path
      this.addGoodsForm.pics = this.addGoodsForm.pics.filter((item) => {
        if (item.pic !== picPath) return item.pic
      })

      // console.log(this.addGoodsForm)
    },
    // 保存添加的商品数据事件
    async add() {
      this.$refs.addGoodsFormRef.validate((valid) => {
        if (!valid) return this.$message.error('请填写必要的表单项！')
      })
      // 深度克隆 this.addGoodsForm
      const form = _.cloneDeep(this.addGoodsForm)
      console.log(this.SaveList)
      // form = this.SaveList
      // 将 goods_cat 数组 转换为字符串
      form.goods_cat = form.goods_cat.join(',')
      // 处理动态属性
      this.manyParamsData.forEach((item) => {
        const newInfo = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals.join(','),
        }
        this.addGoodsForm.attrs.push(newInfo)
        // console.log(this.addGoodsForm.attrs)
      })
      // 处理静态属性
      this.onlyParamsData.forEach((item) => {
        const newInfo = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals.join(','),
        }
        this.addGoodsForm.attrs.push(newInfo)
      })
      form.attrs = this.addGoodsForm.attrs
      console.log(form)

      const { data: res } = await this.$http.post('goods', form)

      if (res.meta.status !== 201) {
        return this.$message.error('添加商品失败！')
      }

      this.$message.success('添加商品成功！')

      this.$router.push('/goods')
    },
  },
}
</script>

<style>
.el-dialog img {
  width: 100%;
}

.btnAdd {
  margin-top: 15px !important;
}
</style>